﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using RN.ERP.Web.Utilities;
using System.Web.SessionState;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.EnterpriseService;
using Fly.Common.Linq;
using Fly.Common.WorkFlow;
using RN.ERP.Web.BasicService;
using Fly.FlyCommon;
using System.Configuration;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// EnterpriseCorpInfo 的摘要说明 
    /// </summary>
    public class EnterpriseCorpInfoHandler : BaseHandler
    {
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private PersonService.PersonServiceClient personServiceClient = new PersonService.PersonServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        public override void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"];
            string data = context.Request["data"];
            string typeFlag = context.Request["typeFlag"];
            string opt = context.Request["opt"];
            string conetent = context.Request["content"];
            string result = "";
            switch (action)
            {
                case "Add":
                    result = Save(data, context);
                    break;
                case "CorpSafeAdd":
                    result = CorpSafeSave(data, context);
                    break;
                case "GetManager":
                    result = GetManager(data);
                    break;
                case "DelManager":
                    result = DelManager(data, typeFlag);
                    break;
                case "GetDictionary":
                    result = GetDictionary(data);
                    break;
                case "AddMarket":
                    result = AddMarket(data);
                    break;
                case "ChangeMarket":
                    result = ChangeMarket(data);
                    break;
                case "CheckCorpByOrgCode":
                    result = CheckCorpByOrgCode(data,context);
                    break;
                case "VerifyCorpReg":
                    result = VerifyCorpReg(context);
                    break;
                case "AuditCorp":
                    result = AuditCorp(data, opt, conetent);
                    break;
                case "CorpSafeAudit":
                    result = CorpSafeAudit(data, opt, conetent);
                    break;
                case "Post":
                    result = Post(context);
                    break;
                case "CorpSafePost":
                    result = CorpSafePost(context);
                    break;
                case "CancelPost":
                    result = CancelPost();
                    break;
                case "SetQueryCondition":
                    result = SetQueryCondition(data);
                    break;
                case "GetCorpZZImage":
                    result = GetCorpZZImage(data);
                    break;
                case "GetCurrentMarket":
                    result = GetCurrentMarket();
                    break;
                case "CorpbCanBid":
                    result = SetCorpbCanBid(context);
                    break;
                case "GetCompanyinfoBusinessInfoKH":
                    result = GetCompanyinfoBusinessInfoKH(context);
                    break;
                case "CompanyAttchInfoKHEdit":
                    result = CompanyAttchInfoKHEdit(context);
                    break;
                case "GetCompanyInfoBySnapGuid":
                    result = GetCompanyInfoBySnapGuid(context);
                    break;
                case "MachineInfoAdd":
                    result = MachineInfoAdd(data,context);
                    break;
                case "MachineInfoEdit":
                    result = MachineInfoEdit(data,context);
                    break;
                case "MachineInfoDel":
                    result=DelCorpMachineInfo(context);
                    break;
                case "FinancialInfoAdd":
                    result = FinancialInfoAdd(data, context);
                    break;
                case "FinancialInfoEdit":
                    result = FinancialInfoEdit(data, context);
                    break;
                case "FinancialInfoDel":
                    result = DelCorpFinancialInfo(context);
                    break;
                case "getMachineInfo":
                    result = GetMachineInfoByID(context);
                    break;
                case "getfinancialInfo":
                    result = GetFinancialInfoByID(context);
                    break;
                case "GetCompanyIntroduction":
                    result = GetCompanyIntroduction(context);
                    break;
                case "AuditCorpOrgCode":
                    result = AuditCorpOrgCode(data, opt, conetent);
                    break;
                case "KaoheGetCompanyInfo":
                    result = KaoheGetCompanyInfo(context);
                    break;
                case "GetCorpFinancialInfo":
                    result = GetCorpFinancialInfoByYear(context);
                    break;
                case "SaveSnap":
                    result = SaveEntitySnapInfo(data, context);
                    break;
                case "GetSnapInfo":
                    result = GetEntitySnapInfo(context);
                    break;
                case "CheckFinancialInfo":
                    result = CheckFinancialInfo(context);
                    break;
                default: break;
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }

        private class RequestValue
        {
            public string name { get; set; }
            public string value { get; set; }
        }

        private string Save(string data, HttpContext context)
        {
            /////begin 判断图片是否上传2013-12-4
            //if (!string.IsNullOrEmpty(context.Request.Params["funcCode"]) && !string.IsNullOrEmpty(context.Request.Params["corpGuid"]))
            //{
            //    string corpGuid = context.Request.Params["corpGuid"].Trim();
            //    string funcCodes = context.Request.Params["funcCode"].TrimEnd(',');
            //    string result0 = UtilitiesTool.IsFileExists(corpGuid, "EF", funcCodes);
            //    if (!string.IsNullOrEmpty(result0))
            //    {
            //        return "{\"Result\":false,\"Message\":\"img\",\"ReturnValue\":\"" + result0 + "\"}";
            //    }
            //}//end
            var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
            string corpInfo = "";
            string khCorpInfo = "";
            string embranchment = "";
            foreach (JsonEntity entity in entities)
            {
                switch (entity.key.ToLower())
                {
                    case "tb_corp_companyinfo":
                        corpInfo = entity.value.Trim('\"');
                        break;
                    case "kh_corptable":
                        khCorpInfo = entity.value.Trim('\"');
                        break;
                    case "tb_corp_embranchment":
                        embranchment = entity.value.Trim('\"');
                        break;
                    default:
                        break;
                }
            }

            string currentAreaCode = UserInfo.CurrentArea;
            var result = enterpriseServiceClient.CorpEdit(corpInfo, khCorpInfo, embranchment, currentAreaCode);
            return result;
        }

        private string CorpSafeSave(string data, HttpContext context)
        {
            var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
            string khCorpInfo = "";
            foreach (JsonEntity entity in entities)
            {
                switch (entity.key.ToLower())
                {
                    case "kh_corptable":
                        khCorpInfo = entity.value.Trim('\"');
                        break;
                    default:
                        break;
                }
            }

            string currentAreaCode = UserInfo.CurrentArea;
            var result = enterpriseServiceClient.KH_CorpEdit(khCorpInfo,currentAreaCode);
            return result;
        }

        private string GetManager(string data)
        {
            Guid userGuid = Guid.Empty;
            if (string.IsNullOrEmpty(data) || !Guid.TryParse(data, out userGuid))
            {
                return string.Empty;
            }
            ////管理人员限定五项3法定代表人4企业负责人5技术负责人7财务负责人8经营负责人
            Dictionary<string, string> managerType = new Dictionary<string, string>();
            managerType.Add("3", "法定代表人");
            managerType.Add("4", "企业负责人");
            managerType.Add("5", "技术负责人");
            managerType.Add("7", "财务负责人");
            managerType.Add("8", "经营负责人");
            string currentAreaCode = UserInfo.CurrentArea;
            List<QueryPersonInfoCondition> list = new List<QueryPersonInfoCondition>();
            foreach (string key in managerType.Keys)
            {
                QueryPersonInfoCondition keyquery = new QueryPersonInfoCondition();
                keyquery.CorpGuid = new Fly.Common.Linq.ParameterValue<Guid>() { V = userGuid, O = OptEnum.Equal };
                keyquery.TypeFlag = new ParameterValue<string>() { V = key, O = OptEnum.Like };
                list.Add(keyquery);
            }
            string condition = JsonConvert.SerializeObject(list);
            //var managerCount = personServiceClient.GetEmpManagerListCount(condition, currentAreaCode);
            var managers = personServiceClient.GetEmpManagersAllList(1, 0, condition, currentAreaCode);
            List<tb_Emp_Manager> listManager = JsonConvert.DeserializeObject<List<tb_Emp_Manager>>(managers);
            List<tb_Emp_Manager> result = new List<tb_Emp_Manager>();
            string title = "";
            foreach (var key in managerType.Keys)
            {
                tb_Emp_Manager existManager = new tb_Emp_Manager();
                var em = listManager.Where(m => m.TypeFlag.Split(',').Contains(key)).FirstOrDefault();
                if (em != null)
                {
                    EntityHelper.ConvertEntity2Entity(em, existManager);
                }
                switch (key)
                {
                    case "3":
                        title = "法定代表人";
                        break;
                    case "4":
                        title = "企业负责人";
                        break;
                    case "5":
                        title = "技术负责人";
                        break;
                    case "7":
                        title = "财务负责人";
                        break;
                    case "8":
                        title = "经营负责人";
                        break;
                    default:
                        title = "";
                        break;
                }
                existManager.TypeFlagTitle = title;
                existManager.TypeFlag = key;
                //身份证电话编码
                existManager.IDCard = UtilitiesTool.GetEcryptStr(UserInfo.CorpUserGuid, UserInfo.RoleType, userGuid.ToString(), existManager.IDCard);
                existManager.Tel = UtilitiesTool.GetEcryptStr(UserInfo.CorpUserGuid, UserInfo.RoleType, userGuid.ToString(), existManager.Tel);
                existManager.MobileTel = UtilitiesTool.GetEcryptStr(UserInfo.CorpUserGuid, UserInfo.RoleType, userGuid.ToString(), existManager.MobileTel);
                result.Add(existManager);
            }
            return JsonConvert.SerializeObject(result);
        }

        private string DelManager(string data, string typeFlag)
        {
            Guid empGuid = Guid.Empty;
            if (string.IsNullOrEmpty(data) || !Guid.TryParse(data, out empGuid))
            {
                return string.Empty;
            }
            string currentAreaCode = UserInfo.CurrentArea;
            string result = personServiceClient.EmpInfoEditTypeFlag(data, typeFlag, currentAreaCode);
            return result;
        }

        private string GetDictionary(string data)
        {
            string currentAreaCode = UserInfo.CurrentArea;
            var result = basicServiceClient.GetDictionary(data, "", currentAreaCode);
            return result;
        }

        private string ChangeMarket(string data)
        {
            string areaCode = data.Length > 2 ? data.Substring(0, 2) : data;
            UserInfo.CurrentArea = areaCode;
            return JsonConvert.SerializeObject(new { Result = true, Message = "修改成功" });
        }

        private string CheckCorpByOrgCode(string data,HttpContext context)
        {
            var roleId = context.Request["roleId"];
            QueryCompanyInfoCondition condition = new QueryCompanyInfoCondition();
            condition.OrginazationCode = new ParameterValue<string>() { V = data, O = OptEnum.Equal };
            List<QueryCompanyInfoCondition> list = new List<QueryCompanyInfoCondition>();
            list.Add(condition);
            var result = enterpriseServiceClient.GetCompaniesInfo(JsonConvert.SerializeObject(list), "");
            var corpInfo = JsonConvert.DeserializeObject<List<Tb_Corp_CompanyInfo>>(result);
            if (corpInfo != null && corpInfo.Count > 0)
            {
                ////2014-4-18 烟台引入招标代理企业（roleid=10506），与原来的代理角色不同，因此允许新旧代理企业同时存在，但不允许相同角色的存在两家
                var roleClassIds = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetDictionary("RoleClassId", "", ""));
                var curRoleClass = roleClassIds.Keys.Contains(roleId)?roleClassIds[roleId]:"";
                int classId = -1;
                if (roleId == "10506")
                {
                    ////判断该类型企业是否已经存在
                    if (int.TryParse(curRoleClass, out classId) && corpInfo.Where(c => c.classID == classId).Count() > 0)
                    {
                        var corp = corpInfo[0];
                        return JsonConvert.SerializeObject(new { Result = true, Message = "该组织机构代码已被【" + corp.CorpName + "】注册", Dogid = corp.dogid });
                    }
                    
                }
                else
                {
                    ////该组织机构代码已存在
                    var corp = corpInfo[0];
                    return JsonConvert.SerializeObject(new { Result = true, Message = "该组织机构代码已被【" + corp.CorpName + "】注册", Dogid = corp.dogid });
                }
            }
            return JsonConvert.SerializeObject(new { Result = false, Message = "该组织机构代码尚未注册", Dogid = -1 });
        }

        private string VerifyCorpReg(HttpContext context)
        {
            string userName = context.Request["userName"];
            string orgCode = context.Request["orgCode"];
            string corpType = context.Request["corpType"];
            EnterpriseServiceClient enterpriseService = new EnterpriseServiceClient();
            int retUser = 0;
            int retOrg = 0;
            //验证用户名
            bool verifyUser = enterpriseService.IsUserExisted(userName, string.Empty);
            if (verifyUser == true)
            {
                retUser = -1;
            }
            else
            {
                retUser = 1;
            }
            //验证组织机构代码
            bool verifyOrgCode = enterpriseService.IsOrgnizationCodeExists(orgCode, corpType, "");
            if (verifyOrgCode == true)
            {
                retOrg = -2;
            }
            else
            {
                retOrg = 2;
            }

            //string output = "{{\"status1\":\"" + retUser.ToString() + "\",\"status2\":\"" + retOrg.ToString() + "\"}}";
            string output = JsonConvert.SerializeObject(new { status1 = retUser, status2 = retOrg });
            return output;
        }

        private string AuditCorp(string data, string opt, string content)
        {
            string currentAreaCode = UserInfo.CurrentArea;
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = UserInfo.CorpUserGuid;
            log.IsrtUserName = UserInfo.Name;
            log.IsrtUserArea = currentAreaCode;
            log.IsrtUserRole = UserInfo.RoleId;
            log.FunctionId = opt;
            log.Content = content;
            var result = enterpriseServiceClient.CorpAudit(data, currentAreaCode, JsonConvert.SerializeObject(log), GetEmbranchmentFlow(currentAreaCode, data), "", false);
            return result;
        }

        private string GetEmbranchmentFlow(object areaCode, string corpUserGuid)
        {
            string flowTitle = "";
            if (areaCode == null)
            {
                return flowTitle;
            }

            string code = areaCode.ToString();
            Tb_Corp_CompanyInfo corpInfo = new Tb_Corp_CompanyInfo();
            corpInfo.CorpUserGuid = Guid.Parse(corpUserGuid);
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), code));
            if (flow != null)
            {
                flowTitle = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            return flowTitle;
        }

        private string CorpSafeAudit(string data, string opt, string content)
        {
            string currentAreaCode = UserInfo.CurrentArea;
            User_Log log = new User_Log();
            log.IsrtDate = DateTime.Now;
            log.IsrtUser = UserInfo.CorpUserGuid;
            log.IsrtUserName = UserInfo.Name;
            log.IsrtUserArea = currentAreaCode;
            log.IsrtUserRole = UserInfo.RoleId;
            log.FunctionId = opt;
            log.Content = content;
            var result = enterpriseServiceClient.CorpSafeAudit(data, currentAreaCode, JsonConvert.SerializeObject(log), GetSecurityFlow(currentAreaCode, data), "", false);
            return result;
        }

        private string GetSecurityFlow(object areaCode, string corpUserGuid)
        {
            string flowTitle = "";
            if (areaCode == null)
            {
                return flowTitle;
            }
            string code = areaCode.ToString();

            var security = JsonConvert.DeserializeObject<Kh_CorpTable>(enterpriseServiceClient.GetCorpSecurity(corpUserGuid, code));
            if (security != null)
            {
                flowTitle = string.IsNullOrEmpty(security.FlowCode) ? "" : security.FlowCode;
            }
            return flowTitle;
        }


        private string Post(HttpContext context)
        {
            ///begin 上报时检测图片是否上传，之前是保存时检测，现在改到上报检测 2014-4-15
            if (!string.IsNullOrEmpty(context.Request.Params["funcCode"]) && !string.IsNullOrEmpty(context.Request.Params["corpGuid"]))
            {
                string corpGuid = context.Request.Params["corpGuid"].Trim();
                string funcCodes = context.Request.Params["funcCode"].TrimEnd(',');
                string result0 = UtilitiesTool.IsFileExists(corpGuid, "EF", funcCodes);
                if (!string.IsNullOrEmpty(result0))
                {
                    return "{\"Result\":false,\"Message\":\"img\",\"ReturnValue\":\"" + result0 + "\"}";
                }
            }//end
            var currentAreaCode = UserInfo.CurrentArea;
            string corpUserGuid = UserInfo.CorpUserGuid;
            string roleId = UserInfo.RoleId;
            var result = enterpriseServiceClient.CorpPost(corpUserGuid, false, false, currentAreaCode);
            return result;
        }

        private string CorpSafePost(HttpContext context)
        {
            ///begin 上报时检测图片是否上传，之前是保存时检测，现在改到上报检测 2014-4-15
            if (!string.IsNullOrEmpty(context.Request.Params["funcCode"]) && !string.IsNullOrEmpty(context.Request.Params["corpGuid"]))
            {
                string corpGuid = context.Request.Params["corpGuid"].Trim();
                string funcCodes = context.Request.Params["funcCode"].TrimEnd(',');
                string result0 = UtilitiesTool.IsFileExists(corpGuid, "EF", funcCodes);
                if (!string.IsNullOrEmpty(result0))
                {
                    return "{\"Result\":false,\"Message\":\"img\",\"ReturnValue\":\"" + result0 + "\"}";
                }
            }//end
            var currentAreaCode = UserInfo.CurrentArea;
            string corpUserGuid = UserInfo.CorpUserGuid;
            string roleId = UserInfo.RoleId;
            var result = enterpriseServiceClient.KH_CorpPost(corpUserGuid, false, false, currentAreaCode);
            return result;
        }
        
        private string CancelPost()
        {
            var currentAreaCode = UserInfo.CurrentArea;
            string corpUserGuid = UserInfo.CorpUserGuid;
            string roleId = UserInfo.RoleId;
            var result = enterpriseServiceClient.CorpCancelPost(corpUserGuid, string.Empty, currentAreaCode);
            return result;
        }

        private string AddMarket(string areaCode)
        {
            string area = areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode;
            var result = JsonConvert.DeserializeObject<OperationResult>(enterpriseServiceClient.EmbranchAdd(UserInfo.CorpUserGuid, area));
            if (result.Result)
            {
                UserInfo.CurrentArea = area;
                return JsonConvert.SerializeObject(new { Result = true, Message = "添加成功" });
            }
            return JsonConvert.SerializeObject(new { Result = false, Message = result.Message });
        }

        private string SetQueryCondition(string data)
        {
            try
            {
                var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                var entity = JsonConvert.DeserializeObject<SeniorEntity>(entities[0].value.Trim('\"'));
                string condition = GetQueryCondition(entity);
                return JsonConvert.SerializeObject(new { Result = true, Message = "", Condition = condition });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = ex.Message });
            }
        }

        private string GetQueryCondition(SeniorEntity senior)
        {
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();

            List<string> listFlow = new List<string>();
            ////角色暂时不处理，等待流程组件的完善
            foreach (var f in senior.Status.Split('|'))
            {
                if (!string.IsNullOrEmpty(f))
                {
                    listFlow.Add(f);
                }
            }
            if (listFlow.Count > 0)
            {
                foreach (var flow in listFlow)
                {
                    var cons = GetCommonQueryCondition(senior);
                    if (cons.Count > 0)
                    {
                        foreach (var con in cons)
                        {
                            con.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = flow };
                            queryCompanyInfoList.Add(con);
                        }
                    }
                    else
                    {
                        QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
                        queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = flow };
                        queryCompanyInfoList.Add(queryCompanyInfoCondition);
                    }
                }
            }
            else
            {
                var cons = GetCommonQueryCondition(senior);
                if (cons.Count > 0)
                {
                    foreach (var con in cons)
                    {
                        con.FlowCode = new ParameterValue<string>() { O = OptEnum.Like, V = "019" };
                        queryCompanyInfoList.Add(con);
                    }
                }
                else
                {
                    QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
                    queryCompanyInfoCondition.FlowCode = new ParameterValue<string>() { O = OptEnum.Like, V = "019" };
                    queryCompanyInfoList.Add(queryCompanyInfoCondition);
                }
            }
            return JsonConvert.SerializeObject(queryCompanyInfoList);
        }

        private List<QueryCompanyInfoCondition> GetCommonQueryCondition(SeniorEntity senior)
        {
            string classId = senior.ClassID;
            string corpName = senior.CorpName;
            string areaCode = senior.AreaCode;
            string flowCode = senior.Status;
            string qualFirst = senior.QualFirst;
            string qualSecond = senior.QualSecond;
            string qualGrade = senior.QualGrade;
            string roleId = senior.RoleId;
            List<QueryCompanyInfoCondition> list = new List<QueryCompanyInfoCondition>();
            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
            int clsId = -1;
            if (!string.IsNullOrEmpty(classId) && int.TryParse(classId, out clsId))
            {
                queryCompanyInfoCondition.classID = new ParameterValue<int?>() { O = OptEnum.Equal, V = clsId };
            }
            if (!string.IsNullOrEmpty(corpName))
            {
                queryCompanyInfoCondition.CorpName = new ParameterValue<string>() { O = OptEnum.Like, V = corpName };
            }
            if (!string.IsNullOrEmpty(areaCode) && areaCode != "-1")
            {
                if (areaCode == "0")
                {
                    ////本地
                    queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = UserInfo.CurrentArea };
                }
                if (areaCode == "1")
                {
                    ////外地
                    queryCompanyInfoCondition.AreaCode = new ParameterValue<string>() { O = OptEnum.NotStartWith, V = UserInfo.CurrentArea };
                }
            }
            if (!string.IsNullOrEmpty(qualGrade) && qualGrade != "-1@-1")
            {
                var grade = qualGrade.Split('@')[0];
                queryCompanyInfoCondition.GradeCode = new ParameterValue<string>() { O = OptEnum.Equal, V = grade };
            }
            if (!string.IsNullOrEmpty(qualSecond) && qualSecond != "-1@-1")
            {
                var code = qualSecond.Split('@')[0];
                int kindId = int.Parse(code);
                queryCompanyInfoCondition.KindID = new ParameterValue<int?>() { O = OptEnum.Equal, V = kindId };
                list.Add(queryCompanyInfoCondition);
            }
            else if (!string.IsNullOrEmpty(qualFirst) && qualFirst != "-1@-1")
            {
                var parentSid = qualFirst.Split('@')[1];
                BasicServiceClient client = new BasicServiceClient();
                var DictQualityInfos = JsonConvert.DeserializeObject<List<DictQualityInfo>>(client.GetQualitiesDic(roleId, parentSid));
                List<int> kindList = new List<int>();
                if (DictQualityInfos != null)
                {
                    foreach (var q in DictQualityInfos)
                    {
                        kindList.Add(int.Parse(q.Code));
                        QueryCompanyInfoCondition newCon = new QueryCompanyInfoCondition();
                        newCon.classID = queryCompanyInfoCondition.classID;
                        newCon.CorpName = queryCompanyInfoCondition.CorpName;
                        newCon.CorpName = queryCompanyInfoCondition.AreaCode;
                        newCon.GradeCode = queryCompanyInfoCondition.GradeCode;
                        newCon.KindID = new ParameterValue<int?>() { O = OptEnum.Equal, V = int.Parse(q.Code) };
                        list.Add(newCon);
                    }
                }
            }
            else
            {
                list.Add(queryCompanyInfoCondition);
            }

            return list;
        }

        private string GetCorpZZImage(string data)
        {
            List<QueryCorpQualityInfoCondition> list = new List<QueryCorpQualityInfoCondition>();
            Guid corpUserGuid = Guid.Empty;
            if (Guid.TryParse(data, out corpUserGuid))
            {
                QueryCorpQualityInfoCondition condition = new QueryCorpQualityInfoCondition();
                condition.CorpUserGuid = new ParameterValue<Guid>() { O = OptEnum.Equal, V = corpUserGuid };
                ////显示所有的资质图片 2014-4-29
                //condition.IsMain = new ParameterValue<bool?>() { O = OptEnum.Equal, V = true };
                list.Add(condition);
                string currentArea = UserInfo == null ? "" : UserInfo.CurrentArea;
                var result = enterpriseServiceClient.GetCorpZZImages(JsonConvert.SerializeObject(list), currentArea);
                return result;
            }
            return "";
        }


        private string GetCurrentMarket()
        {
            string result = "";
            if (string.IsNullOrEmpty(UserInfo.CurrentArea))
            {
                result = "未添加";
            }
            else
            {
                result = UtilitiesTool.GetAreaTitle(UserInfo.CurrentArea);
            }
            return result;
        }

        /// <summary>
        /// 企业锁定解锁
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string SetCorpbCanBid(HttpContext context)
        {
            int corpFlag = 0;
            string corpUserGuid = string.Empty;
            string areaCode = string.Empty;
            int.TryParse(context.Request.Params["corpFlag"], out corpFlag);
            if (context.Request.Params["corpUserGuid"] != null)
            {
                corpUserGuid = context.Request.Params["corpUserGuid"];
            }
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (string.IsNullOrEmpty(corpUserGuid) || string.IsNullOrEmpty(areaCode) || corpFlag == 0)
            {
                return "{\"Result\":false,\"Message\":\"人员信息为空！\"}";
            }

            return enterpriseServiceClient.SetCorpbCanBid(corpUserGuid, corpFlag.ToString(), areaCode);
        }

        /// <summary>
        /// 考核获取企业基本信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCompanyinfoBusinessInfoKH(HttpContext context)
        {
            string corpUserGuid = context.Request["corpUserGuid"];
            string snapGuid = context.Request["snapGuid"];
            return enterpriseServiceClient.GetCompanyBusinessInfoKH(corpUserGuid, snapGuid, UserInfo==null?"":UserInfo.CurrentArea);
        }

        /// <summary>
        /// 考核企业附加信息编辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string CompanyAttchInfoKHEdit(HttpContext context)
        {
            string corpUserGuid = context.Request["corpUserGuid"];
            string capitalInfo = context.Request["capitalInfo"];
            string projectAchieveInfo = context.Request["pAchieveInfo"];
            var result = enterpriseServiceClient.CompanyAttchInfoKHEdit(
                corpUserGuid,
                capitalInfo,
                projectAchieveInfo,
                UserInfo == null ? "" : UserInfo.CurrentArea);
            return result;
        }

        /// <summary>
        /// 根据snapGuid获取企业信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCompanyInfoBySnapGuid(HttpContext context)
        {
            string snapGuid = context.Request["snapGuid"];
            KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient();
            var result =JsonConvert.DeserializeObject<OperationResult>( client.GetCorpSnap(snapGuid, "CorpSnap", UserInfo == null ? string.Empty : UserInfo.CurrentArea));
            return result.ReturnValue.ToString();
        }

        /// <summary>
        /// 添加设备基本信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private string MachineInfoAdd(string data, HttpContext context)
        {
            try
            {
                var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                string MachineInfo = "";
                foreach (JsonEntity entity in entities)
                {
                    switch (entity.key.ToLower())
                    {
                        case "tb_corp_machineinfo":
                            MachineInfo = entity.value.Trim('\"');
                            break;
                        default:
                            break;
                    }
                }
                var model = JsonConvert.DeserializeObject<EnterpriseService.tb_corp_MachineInfo>(MachineInfo);
                model.CorpName = UserInfo.Name;
                model.CorpUserGuid = new Guid(UserInfo.CorpUserGuid);
                model.Creator = UserInfo.UserName;
                model.IsDel = false;
                model.CreateTime = DateTime.Now;
                bool result = client.AddCorpMachineInfo(model, UserInfo.CurrentArea);
                string message = "";
                if (result == true)
                {
                    message = "添加成功！";
                }
                else
                {
                    message = "添加失败！";
                }
                return JsonConvert.SerializeObject(new { Result = result, Message = message });

            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "添加失败！" });
            }
        }

        /// <summary>
        /// 修改设备基本信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private string MachineInfoEdit(string data, HttpContext context)
        {
            try
            {
                var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                string MachineInfo = "";
                foreach (JsonEntity entity in entities)
                {
                    switch (entity.key.ToLower())
                    {
                        case "tb_corp_machineinfo":
                            MachineInfo = entity.value.Trim('\"');
                            break;
                        default:
                            break;
                    }
                }
                var model = JsonConvert.DeserializeObject<EnterpriseService.tb_corp_MachineInfo>(MachineInfo);
                model.CorpName = UserInfo.Name;
                model.CorpUserGuid = new Guid(UserInfo.CorpUserGuid);
                model.Creator = UserInfo.UserName;
                model.IsDel = false;
                bool result = client.UpdateCorpMachineInfo(model, UserInfo.CurrentArea);
                string message = "";
                if (result == true)
                {
                    message = "修改成功！";
                }
                else
                {
                    message = "修改失败！";
                }
                return JsonConvert.SerializeObject(new { Result = result, Message = message });

            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "修改失败！" });
            }
        }

        /// <summary>
        /// 删除机械设备基本信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private string DelCorpMachineInfo( HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["id"]);
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                bool result = client.DelCorpMachineInfo(id, UserInfo.CurrentArea);
                string message = "";
                if (result == true)
                {
                    message = "删除成功！";
                }
                else
                {
                    message = "删除失败！";
                }
                return JsonConvert.SerializeObject(new { Result = result, Message = message });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "删除失败" });
            }
        }

        /// <summary>
        /// 新增企业财务经营情况
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string FinancialInfoAdd(string data, HttpContext context)
        {
            var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
            string financialInfo = "";
            foreach (JsonEntity entity in entities)
            {
                switch (entity.key.ToLower())
                {
                    case "tb_corp_financialinfo":
                        financialInfo = entity.value.Trim('\"');
                        break;
                    default:
                        break;
                }
            }
            try
            {
                var model = JsonConvert.DeserializeObject<tb_corp_FinancialInfo>(financialInfo);
                model.CorpName = UserInfo.Name;
                model.CorpUserGuid = new Guid(UserInfo.CorpUserGuid);
                model.Creator = UserInfo.UserName;
                model.IsDel = false;
                model.CurrentYear = Convert.ToInt32(DateTime.Now.AddYears(-1).ToString("yyyy"));
                string currentAreaCode = UserInfo.CurrentArea;
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                var result = client.AddCorpFinancialInfo(model, currentAreaCode);
                string message = "";
                if (result == true)
                {
                    message = "添加成功！";
                }
                else
                {
                    message = "添加失败！";
                }
                return JsonConvert.SerializeObject(new { Result = result, Message = message });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "添加失败" });
            }
        }

        /// <summary>
        /// 修改企业财务经营情况
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string FinancialInfoEdit(string data, HttpContext context)
        {
            var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
            string financialInfo = "";
            foreach (JsonEntity entity in entities)
            {
                switch (entity.key.ToLower())
                {
                    case "tb_corp_financialinfo":
                        financialInfo = entity.value.Trim('\"');
                        break;
                    default:
                        break;
                }
            }
            try
            {
                var model = JsonConvert.DeserializeObject<tb_corp_FinancialInfo>(financialInfo);
                model.CorpName = UserInfo.Name;
                model.CorpUserGuid = new Guid(UserInfo.CorpUserGuid);
                model.Creator = UserInfo.UserName;
                string currentAreaCode = UserInfo.CurrentArea;
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                var result = client.UpdateCorpFinancialInfo(model, currentAreaCode);
                string message = "";
                if (result == true)
                {
                    message = "修改成功！";
                }
                else
                {
                    message = "修改失败！";
                }
                return JsonConvert.SerializeObject(new { Result = result, Message = message });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "修改失败" });
            }
        }

        /// <summary>
        /// 删除企业财务经营情况
        /// </summary>
        /// <param name="data"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private string DelCorpFinancialInfo(HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["id"]);
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                bool result = client.DelCorpFinancialInfo(id, UserInfo.CurrentArea);
                string message = "";
                if (result == true)
                {
                    message = "删除成功！";
                }
                else
                {
                    message = "删除失败！";
                }
                return JsonConvert.SerializeObject(new { Result = result, Message = message });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "删除失败" });
            }
        }

        /// <summary>
        /// 根据ID获取企业设备基本信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetMachineInfoByID(HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["mid"]);
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                string result = client.GetCorpMachineInfoByID(new Guid(UserInfo.CorpUserGuid),id, UserInfo.CurrentArea);
                return"{ \"Result\" : true, \"Message\" : \"获取成功\", \"ReturnValue\" : "+result+" }";
            }
            catch (Exception ex)
            {
                return "{ \"Result\" : false, \"Message\" : \"获取失败\" }";
            }
        }

        /// <summary>
        /// 根据ID获取企业财务基本信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetFinancialInfoByID(HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["mid"]);
                EnterpriseService.EnterpriseServiceClient client = new EnterpriseService.EnterpriseServiceClient();
                string result = client.GetCorpFinancialInfoByID(new Guid(UserInfo.CorpUserGuid), id, UserInfo.CurrentArea);
                return "{ \"Result\" : true, \"Message\" : \"获取成功\", \"ReturnValue\" : "+result+" }";
            }
            catch (Exception ex)
            {
                return "{ \"Result\" : false, \"Message\" : \"获取失败\" }";
            }
        }

        /// <summary>
        /// 年检获取企业基本信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string KaoheGetCompanyInfo(HttpContext context)
        {
            string corpUserGuid = string.Empty;
            if (string.IsNullOrEmpty(context.Request["corpUserGuid"]))
            {
                corpUserGuid = UserInfo.CorpUserGuid;
            }
            else
            {
                corpUserGuid = context.Request["corpUserGuid"];
            }
            QueryCompanyInfoCondition queryCompanyInfoCondition =
               new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(corpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var corpInfo = enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea);
            return corpInfo;
        }

        /// <summary>
        /// 根据年份获取财务信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCorpFinancialInfoByYear(HttpContext context)
        {
            Guid corpUserGuid=new Guid();
            if (string.IsNullOrEmpty(context.Request["corpUserGuid"]))
            {
                corpUserGuid = new Guid(UserInfo.CorpUserGuid);
            }
            else
            {
                Guid.TryParse(context.Request["corpUserGuid"], out corpUserGuid);
            }
            int currentYear = Convert.ToInt32(context.Request["year"]) - 1;
            EnterpriseService.EnterpriseServiceClient client = new EnterpriseServiceClient();
            string result = client.GetCorpFinancialInfoByYear(corpUserGuid, currentYear, UserInfo.CurrentArea);
            return result;
        }

        /// <summary>
        /// 获取企业简介
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCompanyIntroduction(HttpContext context)
        {
            string corpUserGuid = string.Empty;
            if (string.IsNullOrEmpty(context.Request["corpUserGuid"]))
            {
                corpUserGuid = UserInfo.CorpUserGuid;
            }
            else
            {
                corpUserGuid = context.Request["corpUserGuid"];
            }
            QueryCompanyInfoCondition queryCompanyInfoCondition =
               new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(corpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var corpInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea));
            return "{ \"Introduction\" : \"" + corpInfo.Introduction + "\"}";
        }

        /// <summary>
        /// 读取快照信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetEntitySnapInfo(HttpContext context)
        {
            string entityGuid = string.Empty;
            int snapKind = 0;
            if (!string.IsNullOrEmpty(context.Request["corpUserGuid"]))
            {
                entityGuid = context.Request["corpUserGuid"];
            }
            else
            {
                entityGuid = UserInfo.CorpUserGuid;
            }
            if (!string.IsNullOrEmpty(context.Request["snapKind"]))
            {
                snapKind = Convert.ToInt32(context.Request["snapKind"]);
            }
            try
            {
                using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
                {
                    string result = client.GetEntitySnapInfo(entityGuid, snapKind);
                    var rst = JsonConvert.DeserializeObject<ModelService.OperationResult>(result);
                    if (rst.ReturnValue != null)
                    {
                        var model = JsonConvert.DeserializeObject<ModelService.EntitySnap>(rst.ReturnValue.ToString());
                        return "{ \"ID\" : \"" + model.Id.ToString() + "\",\"SnapGuid\" : \"" + model.KeyGuid.ToString() + "\", \"SnapData\" : " + model.SnapData + " }";
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 保存快照信息
        /// </summary>
        /// <param name="data"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private string SaveEntitySnapInfo(string data, HttpContext context)
        {
            var entities = JsonConvert.DeserializeObject<List<JsonEntity>>(data);
            string snapData = "";
            int snapKind = 0;
            foreach (JsonEntity entity in entities)
            {
                switch (entity.key.ToLower())
                {
                    case "companyinfokh":
                        snapData = entity.value.Trim('\"');
                        snapKind = 1000;
                        break;
                    case "tb_corp_financialinfo":
                        snapData = entity.value.Trim('\"');
                        snapKind = 1001;
                        break;
                    case "machinestatistics":
                        snapData = entity.value.Trim('\"');
                        snapKind = 1002;
                        break;
                    case "companyprofile":
                        snapData = entity.value.Trim('\"');
                        snapKind = 1003;
                        break;
                    case "rewardandpunish":
                        snapData = entity.value.Trim('\"');
                        snapKind = 1004;
                        break;
                    default:
                        break;
                }
            }
            try
            {
                EntitySnap model = new EntitySnap();
                model.SnapData = snapData;
                model.EntityGuid = new Guid(UserInfo.CorpUserGuid);
                if (string.IsNullOrEmpty(context.Request["snapGuid"]))
                {
                    model.KeyGuid = Guid.NewGuid();
                    model.Id = 0;
                }
                else
                {
                    model.KeyGuid = new Guid(context.Request["snapGuid"]);
                    model.Id = Convert.ToInt32(context.Request["ID"]);
                }
                model.SnapKind = snapKind;
                model.IsDel = false;
                model.IsrtDate = DateTime.Now;
                model.AppId = "101";
                model.AreaCode = "14";
                model.Year = DateTime.Now.Year.ToString();
                string result = string.Empty;
                string strModel = JsonConvert.SerializeObject(model);
                using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
                {
                    result = client.SaveEntitySnapInfo(strModel);
                }
                return result;
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { Result = false, Message = "保存失败" });
            }
        }

        /// <summary>
        /// 主管审核组织机构代码变更
        /// </summary>
        /// <param name="data"></param>
        /// <param name="opt"></param>
        /// <param name="conetent"></param>
        /// <returns></returns>
        private string AuditCorpOrgCode(string guid, string opt, string conetent)
        {
            string[] corpUserGuid = guid.Split(',');
            string roleId = UserInfo.RoleId;
            string areaCode = UserInfo.CurrentArea;
            int codeType = 1400;////聊城变更组织机构代码的classid
            int appID = 0;
            string appIDStr = ConfigurationManager.AppSettings["AppId"] != null ? ConfigurationManager.AppSettings["AppId"] : "";
            int.TryParse(appIDStr, out appID);
            int optType = 0;
            int.TryParse(opt, out optType);

            string resultStr = enterpriseServiceClient.CorpOrgAudit(corpUserGuid, roleId, areaCode, codeType, appID, optType);

            var operate = JsonConvert.DeserializeObject<OperationResult>(resultStr);
            if (operate.Result && optType == 5)
            {
                string fileName = guid + ".jpg";
                using (FileService.FileWebServiceSoapClient client = new FileService.FileWebServiceSoapClient())
                {
                    string isSuccess = client.MoveFileFromOneToAnother(fileName, "EF", "CorpORGChange", fileName, "EF", "CorpORG");
                }
            }

            return resultStr;
        }


        private string CheckFinancialInfo(HttpContext context)
        {
            string corpGuidStr = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["CorpUserGuid"]))
            {
                corpGuidStr = context.Request.Params["CorpUserGuid"];
            }
            Guid corpGuid = Guid.Empty;
            Guid.TryParse(corpGuidStr, out corpGuid);

            int count = 0;
            int currentYear = 0;
            string areaCode = UserInfo.CurrentArea;
            string currentYearStr = DateTime.Now.AddYears(-1).ToString("yyyy");
            int.TryParse(currentYearStr, out currentYear);

            var result = enterpriseServiceClient.GetCorpFinancialInfoList(out count, "", 1, 10, corpGuid, currentYear, areaCode);
            //var list = JsonConvert.DeserializeObject<IList<tb_corp_FinancialInfo>>(result);

            return JsonConvert.SerializeObject(new { Count = count });
        }

    }
    public class SeniorEntity
    {
        public string Status { get; set; }
        public string AreaCode { get; set; }
        public string CorpName { get; set; }
        public string QualFirst { get; set; }
        public string QualSecond { get; set; }
        public string QualGrade { get; set; }
        public string ClassID { get; set; }
        public string RoleId { get; set; }

    }
}
